package cn.com.idmy.auth.oauth;

import cn.com.idmy.auth.exception.AuthException;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;


import java.util.Map;

public class JwtTokenUtil {
    public static String of(@Nullable Object id, @Nullable Map<String, Object> payload, Algorithm algorithm, long exp) {
        if (id == null && payload == null) {
            throw new AuthException("id和payload不能同时为空");
        }
        JSONObject header = new JSONObject(2);
        //header.put("nonce", IdUtil.fastSimpleUUID());
        if (id != null) {
            header.put("id", id);
        }
        header.put("exp", exp);
        return JWT.create()
                .withHeader(header)
                .withPayload(payload)
                .sign(algorithm);
    }

    public static Object parseId(String token, Algorithm algorithm) {
        JWTVerifier verifier = JWT.require(algorithm);
        DecodedJWT decodedJWT = verifier.verify(token);
        Claim id = decodedJWT.getHeaderClaim("id");
        return id.as(Object.class);
    }
}
